package com.keldian.mobilesafe.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.Looper;
import android.util.Log;
import android.util.Xml;
import android.widget.Toast;

import com.keldian.mobilesafe.domain.SmsItem;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlSerializer;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 16-1-7.
 */
public class SmsUtils {
    private static List<SmsItem> smsItems;

    public interface BackupCallBack {

        public void beforeBackup(int max);

        public void onSmsBackup(int progress);
    }


    public static void backupSms(Context context, BackupCallBack callBack) throws Exception {
        Thread.sleep(500);
        ContentResolver resolver = context.getContentResolver();
        File file = new File(Environment.getExternalStorageDirectory(), "backupSms.xml");

        FileOutputStream fos = new FileOutputStream(file);
        XmlSerializer serializer = Xml.newSerializer();

        serializer.setOutput(fos, "utf-8");
        serializer.startDocument("utf-8", true);
        serializer.startTag(null, "smss");

        Uri uri = Uri.parse("content://sms/");
        Cursor cursor = resolver.query(uri, new String[]{"body", "address", "type", "date"}, null, null, null);

        int max = cursor.getCount();
        callBack.beforeBackup(max);

        serializer.attribute(null, "max", max + "");
        int process = 0;
        while (cursor.moveToNext()) {
            String body = cursor.getString(0);
            String address = cursor.getString(1);
            String type = cursor.getString(2);
            String date = cursor.getString(3);
            //写入Xml文件
            serializer.startTag(null, "sms");

            serializer.startTag(null, "body");
            serializer.text(body);
            serializer.endTag(null, "body");

            serializer.startTag(null, "address");
            serializer.text(address);
            serializer.endTag(null, "address");

            serializer.startTag(null, "type");
            serializer.text(type);
            serializer.endTag(null, "type");

            serializer.startTag(null, "date");
            serializer.text(date);
            serializer.endTag(null, "date");

            serializer.endTag(null, "sms");
            process++;
            callBack.onSmsBackup(process);

        }


        cursor.close();

        serializer.endTag(null, "smss");
        serializer.endDocument();
        fos.close();
    }


    public static void retoreSms(Context context, boolean flag, BackupCallBack callBack) throws Exception {
        int max = 0;
        int process = 0;
        SmsItem smsItem = null;
        Uri uri = Uri.parse("content://sms");
        if (flag) {
            context.getContentResolver().delete(uri, null, null);
        }
        XmlPullParser pullParser = Xml.newPullParser();
        String absolutePath = Environment.getExternalStorageDirectory() + "/backupSms.xml";
        Log.d("SmsUtils", absolutePath);
        File file = new File(absolutePath);

        if (!file.exists()) {
            Looper.prepare();
            Toast.makeText(context, "xml短信备份文件不在sd卡中", Toast.LENGTH_SHORT).show();
            Looper.loop();
        }

        FileInputStream fis = new FileInputStream(file);
        pullParser.setInput(fis, "UTF-8");


        try {

            int event = pullParser.getEventType();
            while (event != XmlPullParser.END_DOCUMENT) {
                switch (event) {
                    case XmlPullParser.START_DOCUMENT:
                        smsItems = new ArrayList<SmsItem>();
                        break;
                    case XmlPullParser.START_TAG:
                        if ("smss".equals(pullParser.getName())) {
                            smsItem = new SmsItem();
                            Log.i("TAG", "smss" + pullParser.getAttributeValue(0));
                            max = Integer.parseInt(pullParser.getAttributeValue(0));
                        }

                        if ("sms".equals(pullParser.getName())) {
                            Log.i("tag", "start-sms---" + pullParser.getName());
                        }
                        Log.i("tag", "wb---" + pullParser.getName());
                        if ("body".equals(pullParser.getName()) && smsItem != null) {
                            String body = pullParser.nextText();
                            Log.i("tag", "body---" + body);
                            smsItem.setBody(body);
                        }
                        if ("address".equals(pullParser.getName()) && smsItem != null) {
                            String address = pullParser.nextText();
                            Log.i("tag", "address---" + address);
                            smsItem.setAddress(address);
                        }
                        if ("type".equals(pullParser.getName()) && smsItem != null) {
                            String type = pullParser.nextText();
                            Log.i("tag", "type---" + type);
                            smsItem.setType(type);
                        }
                        if ("date".equals(pullParser.getName()) && smsItem != null) {
                            String date = pullParser.nextText();
                            Log.i("tag", "date---" + date);
                            smsItem.setDate(date);
                            smsItems.add(smsItem);
                            smsItem = null;
                            smsItem = new SmsItem();
                        }
                        break;
                    case XmlPullParser.END_TAG:
                        if ("sms".equals(pullParser.getName())) {
                            Log.i("tag", "end--sms---" + pullParser.getName());
                        }
                        if ("smss".equals(pullParser.getName())) {
                            Log.i("tag", "end--sms---" + pullParser.getName());
                            smsItem = null;
                        }
                        break;
                }
                event = pullParser.next();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            Looper.prepare();
            Toast.makeText(context, "短信恢复出错", 1).show();
            Looper.loop();
            e.printStackTrace();

        } catch (XmlPullParserException e) {
            // TODO Auto-generated catch block
            Looper.prepare();
            Toast.makeText(context, "短信恢复出错", 1).show();
            Looper.loop();
            e.printStackTrace();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            Looper.prepare();
            Toast.makeText(context, "短信恢复出错", 1).show();
            Looper.loop();
            e.printStackTrace();
        }

        Log.d("SmsUtils", smsItems.size() + "");
        callBack.beforeBackup(max);

        ContentValues values = new ContentValues();

        for (int i = 0; i < smsItems.size(); i++) {
            values.put("body", smsItems.get(i).getBody());
            values.put("date", smsItems.get(i).getDate());
            values.put("type", smsItems.get(i).getType());
            values.put("address", smsItems.get(i).getAddress());
            context.getContentResolver().insert(uri, values);
            process++;
            callBack.onSmsBackup(process);
        }

//        for (SmsItem sms : smsItems) {
//
//        }

        // 1.读取sd卡上的xml文件
        // Xml.newPullParser();

        // 2.读取max

        // 3.读取每一条短信信息，body date type address

        // 4.把短信插入到系统短息应用。

    }


}
